﻿namespace StationDataHub.TimeJob;

/// <summary>
/// 获取Token
/// </summary>
public class GetTokenkJob(IFlurlClientCache client, IEasyCachingProvider factory) : IJob
{
    private readonly IFlurlClient _client = client.Get("ChargePlatform");
    private readonly IEasyCachingProvider _cache = factory;

    public async Task Execute(IJobExecutionContext context)
    {
        var cfg = AppSettings.ChargePlatform.SecurityConfig;
        // 构造请求体
        var reqBody = new
        {
            cfg.OperatorID,
            cfg.OperatorSecret
        }.BuildEncryptedRequest();

        var response = await _client.Request(AppSettings.ChargePlatform.API.Interfaces.GetAuthToken)
            .PostJsonAsync(reqBody)
            .ReceiveString();
        var tokenResp = JsonSerializer.Deserialize<APIResponse>(response);
        if (tokenResp != null && tokenResp.Ret == 0)
        {
            // 解密tokenResp.Data并反序列化为TokenResponse
            var decrypted = tokenResp.Data.DecryptAES(cfg.AesEncryptionKey, cfg.AesInitialVector);
            var tokenData = JsonSerializer.Deserialize<TokenResponse>(decrypted);
            if (tokenData != null && tokenData.SuccStat == 0)
            {
                var token = tokenData.AccessToken;
                var ttl = TimeSpan.FromSeconds(tokenData.TokenAvailableTime - 60); // 提前过期
                await _cache.SetAsync("ChargePlatformToken", token, ttl);
                Log.Information($"刷新Token成功，有效期 {ttl.TotalMinutes} 分钟");
            }
            else
            {
                Log.Error($"刷新Token失败，FailReason={tokenData?.FailReason}");
            }
        }
    }
}